﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static LiWi.Shell;

namespace WindowsFormsApp1
{

    public partial class Form1 : Form
    {
        Axisparam axisparam = new Axisparam();

        float[] axisSpeed;      //轴速
        float[] axisAccel;      //轴加速
        float[] axisDecel;      //轴减速        
        float[] dPosValue;      //轴位置
        bool[] axisFlag;        //轴标志；0停止，1运行
        IntPtr _handle = IntPtr.Zero;




        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            axisparam.isConnect = false;
            lab_NowState.Text = "未连接";
            lab_NowState.BackColor = Color.Red;
            closeEnable();

        }

        public void ToDoJob()
        {
            if (axisparam.isConnect)
            {
                Button[] btnjogRed = new Button[axisparam.MotorMaxNum];  //创建轴的+按钮
                Button[] btnjogAdd = new Button[axisparam.MotorMaxNum];  //创建轴的-按钮
                List<int> axisMap = new List<int>();
                for (int i = 0; i < axisparam.MotorMaxNum; i++)
                {
                    axisMap.Add(i);
                }
                for (int i = 0; i < axisparam.MotorMaxNum; i++)
                {

                    int axis = axisMap[i];
                    var btnjog_red = "btnJOGRed" + (i + 1);
                    var btnjog_add = "btnJOGAdd" + (i + 1);
                    btnjogRed[i] = this.Controls.Find(btnjog_red, true).FirstOrDefault() as Button;
                    btnjogAdd[i] = this.Controls.Find(btnjog_add, true).FirstOrDefault() as Button;
                    btnjogRed[i].MouseDown += (sender, e) =>                   //按下按钮
                    {
                        JOGSport(axis, axisparam.isConnect, false, true);
                    };
                    btnjogRed[i].MouseUp += (sender, e) =>                     //松开按钮
                    {
                        JOGSport(axis, axisparam.isConnect, false, false);

                    };

                    btnjogAdd[i].MouseDown += (sender, e) =>                   //按下按钮
                    {
                        JOGSport(axis, axisparam.isConnect, true, true);
                    };
                    btnjogAdd[i].MouseUp += (sender, e) =>
                    {
                        JOGSport(axis, axisparam.isConnect, false, false);

                    };


                }

                btnGoPoint.Click += (sender, e) =>
                {
                    Thread th = new Thread(GoPoin);
                   //GoPoinAsync();
                   th.Start();
                };
            }

        }

        /// <summary>
        /// JOG 运动
        /// </summary>
        /// <param name="iaxis">轴号</param>
        /// <param name="isConnect">连接状态</param>
        /// <param name="Add">+，—</param>
        /// <param name="anzhe">是否按着</param>
        public void JOGSport(int iaxis, bool isConnect, bool Add, bool anzhe)
        {
            var isSport = isPower(true);
            if (isConnect && !isSport)
            {
                int flag = Add ? 1 : -1;
                int[] axisnum = { iaxis };
                PMC_Base(_handle, 1, axisnum);

                if (anzhe )
                {
                    PMC_Single_Vmove(_handle, iaxis, flag);           //连续运动：1正向，-1负向
                    PMC_SetOp(_handle, 3, 1);
                }
                else
                {
                    PMC_Stop(_handle);
                }
            }
            else MessageBox.Show("请检查连接状态和轴运行状态");
        }





        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_connect_Click(object sender, EventArgs e)
        {
            if (but_connect.Text == "连接")
            {
                openConnect();
                loadPointSport(axisparam.isConnect, axisparam.MotorMaxNum);
                if (axisparam.isConnect) but_connect.Text = "断开";
            }
            else
            {
                closeConnect();
                if (!axisparam.isConnect) but_connect.Text = "连接";
            }


        }

        /// <summary>
        /// 连接
        /// </summary>
        public void openConnect()
        {
            //TCP链接
            string _ip = box_TCPIPselect.Text.ToString();
            int ret = PMC_OpenEth(_ip, ref _handle);
            if (ret == 0)
            {

                axisparam.isConnect = true;
                lab_NowState.Text = "已连接";
                lab_NowState.BackColor = Color.Green;
                PMC_GetControllerName(_handle, axisparam.NameVersion);          //驱动器名称
                PMC_GetIdentifier(_handle, ref axisparam.Identifier);           //序列号
                PMC_GetIdHardware(_handle, ref axisparam.HardNum);              //硬件编号
                PMC_GetIdSoftware(_handle, ref axisparam.SoftNum);              //软件编号
                PMC_GetHardVersion(_handle, ref axisparam.HardVersion);         //硬件版本
                PMC_GetSoftwareVersion(_handle, ref axisparam.SoftVersion);     //软件版本
                PMC_GetSysSpecification(_handle, ref axisparam.VirAxisMaxNum, ref axisparam.MotorMaxNum, axisparam.MotorMaxIO);
                lab_ControllerName.Text = Encoding.ASCII.GetString(axisparam.NameVersion);
                lab_Identifier.Text = axisparam.Identifier.ToString();
                lab_HardNum.Text = axisparam.HardNum.ToString();
                lab_SoftNum.Text = axisparam.SoftNum.ToString();
                lab_HardVersion.Text = axisparam.HardVersion.ToString();
                lab_SoftVersion.Text = axisparam.HardVersion.ToString();
                lab_virAxisMaxNum.Text = axisparam.VirAxisMaxNum.ToString();
                lab_motorMaxNum.Text = axisparam.MotorMaxNum.ToString();
                lab_INMaxNum.Text = axisparam.MotorMaxIO[0].ToString();
                lab_OUTMaxNum.Text = axisparam.MotorMaxIO[1].ToString();
                lab_ADMaxNum.Text = axisparam.MotorMaxIO[2].ToString();
                lab_DAMaxNum.Text = axisparam.MotorMaxIO[3].ToString();

                axisSpeed = new float[axisparam.VirAxisMaxNum];         //轴速
                axisAccel = new float[axisparam.VirAxisMaxNum];         //轴加速
                axisDecel = new float[axisparam.VirAxisMaxNum];         //轴减速                
                dPosValue = new float[axisparam.VirAxisMaxNum];         //轴位置
                axisFlag = new bool[axisparam.VirAxisMaxNum];            //轴标志；0停止，1运行

                axisparam.IP = box_TCPIPselect.Text;


                //for(int i=0; i<axisparam.MotorMaxNum; i++)
                //{
                //    int[] axislist = { i };
                //    float pfvaule = 0;
                //    PMC_Base(_handle, 1, axislist);
                //    PMC_SetUnits(_handle,i,200);
                //    PMC_GetUnits(_handle, i, ref pfvaule);
                //    Console.WriteLine($"轴{i}units值为{pfvaule}");
                //}




                ShowOrWritePara();

                ToDoJob();

                for (int i = 0; i < axisparam.MotorMaxNum; i++)
                {
                    PMC_SetAxisEnable(_handle, i, 1);
                    PMC_SetAtype(_handle, i, 1);
                    PMC_SetDpos(_handle, i, 0);
                    PMC_SetUnits(_handle, i, 200);
                    PMC_SetSramp(_handle, i, 5000);
                }

                MessageBox.Show("连接成功！！！！");
            }

            else
            {
                MessageBox.Show("连接失败！！！！");
            }
        }

        /// <summary>
        /// 断开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void closeConnect()
        {

            int ret = PMC_Close(_handle);
            if (ret == 0)
            {
                lab_ControllerName.Text = "-1";
                lab_Identifier.Text = "-1";
                lab_HardNum.Text = "-1";
                lab_SoftNum.Text = "-1";
                lab_HardVersion.Text = "-1";
                lab_SoftVersion.Text = "-1";
                lab_virAxisMaxNum.Text = "-1";
                lab_motorMaxNum.Text = "-1";
                lab_INMaxNum.Text = "-1";
                lab_OUTMaxNum.Text = "-1";
                lab_ADMaxNum.Text = "-1";
                lab_DAMaxNum.Text = "-1";
                MessageBox.Show("关闭成功");
                axisparam.isConnect = false;
                lab_NowState.Text = "未连接";
                lab_NowState.BackColor = Color.Red;
                closeEnable();
            }
            else MessageBox.Show("关闭失败");

        }

        /// <summary>
        /// JOG:X+
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnJOGAddX_Click(object sender, EventArgs e)
        {


        }
        /// <summary>
        /// 设置轴参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SavePara_Click(object sender, EventArgs e)
        {
            if (axisparam.isConnect)
            {
                ShowOrWritePara(false);

                MessageBox.Show("保存成功！！！");
            }
            else
            {
                MessageBox.Show("请先连接控制器");
            }
        }



        /// <summary>
        /// 读取、写入轴参数
        /// </summary>
        /// <param name="read">是否读取</param>
        public void ShowOrWritePara(bool read = true)
        {
            if (axisparam.isConnect)
            {
                btn_SavePara.Visible = true;
                if (read)   // 读取轴
                {
                    if (axisparam.MotorMaxNum > 4)
                    {
                        label31.Visible = true;
                        label32.Visible = true;
                        label33.Visible = true;
                        label34.Visible = true;
                        label35.Visible = true;
                        label36.Visible = true;
                    }
                    else if (axisparam.MotorMaxNum > 0)
                    {
                        label31.Visible = true;
                        label32.Visible = true;
                        label33.Visible = true;
                    }
                    for (int i = 0; i < axisparam.MotorMaxNum; i++)
                    {
                        axisSpeed[i] = 0;
                        axisAccel[i] = 0;
                        axisDecel[i] = 0;
                        PMC_GetSpeed(_handle, i, ref axisSpeed[i]);
                        PMC_GetSpeed(_handle, i, ref axisAccel[i]);
                        PMC_GetSpeed(_handle, i, ref axisDecel[i]);

                        var num_speed = "num_Speed_" + (i + 1);
                        var num_accel = "num_Accel_" + (i + 1);
                        var num_decel = "num_Decel_" + (i + 1);
                        var btn_JOGRed = "btnJOGRed" + (i + 1);
                        var btn_JOGAdd = "btnJOGAdd" + (i + 1);
                        var numspeed = this.Controls.Find(num_speed, true).FirstOrDefault() as NumericUpDown;
                        var numaccel = this.Controls.Find(num_accel, true).FirstOrDefault() as NumericUpDown;
                        var numdecel = this.Controls.Find(num_decel, true).FirstOrDefault() as NumericUpDown;
                        var btnJOGRed = this.Controls.Find(btn_JOGRed, true).FirstOrDefault() as Button;
                        var btnJOGAdd = this.Controls.Find(btn_JOGAdd, true).FirstOrDefault() as Button;

                        numspeed.Enabled = true;
                        numaccel.Enabled = true;
                        numdecel.Enabled = true;
                        btnJOGAdd.Enabled = true;
                        btnJOGRed.Enabled = true;

                        numspeed.Visible = true;
                        numaccel.Visible = true;
                        numdecel.Visible = true;
                        btnJOGAdd.Visible = true;
                        btnJOGRed.Visible = true;

                        numspeed.Value = (decimal)axisSpeed[i];
                        numaccel.Value = (decimal)axisAccel[i];
                        numdecel.Value = (decimal)axisDecel[i];

                        var lable_num = "";
                        if (i < 9) lable_num = "label5" + (i + 1);
                        else lable_num = "label6" + (i - 9);
                        var lableNum = this.Controls.Find(lable_num, true).FirstOrDefault() as Label;
                        lableNum.Visible = true;
                    }

                }
                else    //写入轴
                {
                    for (int i = 0; i < axisparam.MotorMaxNum; i++)
                    {
                        var num_speed = "num_Speed_" + (i + 1);
                        var num_accel = "num_Accel_" + (i + 1);
                        var num_decel = "num_Decel_" + (i + 1);

                        var numspeed = this.Controls.Find(num_speed, true).FirstOrDefault() as NumericUpDown;
                        var numaccel = this.Controls.Find(num_accel, true).FirstOrDefault() as NumericUpDown;
                        var numdecel = this.Controls.Find(num_decel, true).FirstOrDefault() as NumericUpDown;

                        axisSpeed[i] = (float)numspeed.Value;
                        axisAccel[i] = (float)numaccel.Value;
                        axisDecel[i] = (float)numdecel.Value;
                        PMC_SetSpeed(_handle, i, axisSpeed[i]);
                        PMC_SetAccel(_handle, i, axisAccel[i]);
                        PMC_SetDecel(_handle, i, axisDecel[i]);
                    }
                }

            }
            else
            {
                MessageBox.Show("请先连接控制器");
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            if (axisparam.isConnect)
            {
                //setAxisParamenter();
            }
        }

        /// <summary>
        /// 关闭控件功能
        /// </summary>
        public void closeEnable()
        {
            label31.Visible = false;
            label32.Visible = false;
            label33.Visible = false;
            label34.Visible = false;
            label35.Visible = false;
            label36.Visible = false;
            btn_SavePara.Visible = false;
            for (int i = 0; i < 16; i++)
            {
                //轴速，加减速，JOG+，-
                var num_speed = "num_Speed_" + (i + 1);
                var num_accel = "num_Accel_" + (i + 1);
                var num_decel = "num_Decel_" + (i + 1);
                var btn_JOGRed = "btnJOGRed" + (i + 1);
                var btn_JOGAdd = "btnJOGAdd" + (i + 1);
                var numspeed = this.Controls.Find(num_speed, true).FirstOrDefault() as NumericUpDown;
                var numaccel = this.Controls.Find(num_accel, true).FirstOrDefault() as NumericUpDown;
                var numdecel = this.Controls.Find(num_decel, true).FirstOrDefault() as NumericUpDown;
                var btnJOGRed = this.Controls.Find(btn_JOGRed, true).FirstOrDefault() as Button;
                var btnJOGAdd = this.Controls.Find(btn_JOGAdd, true).FirstOrDefault() as Button;
                numspeed.Value = 0;
                numaccel.Value = 0;
                numdecel.Value = 0;
                numspeed.Enabled = false;
                numaccel.Enabled = false;
                numdecel.Enabled = false;
                btnJOGAdd.Enabled = false;
                btnJOGRed.Enabled = false;

                numspeed.Visible = false;
                numaccel.Visible = false;
                numdecel.Visible = false;
                btnJOGAdd.Visible = false;
                btnJOGRed.Visible = false;

                var lable_num = "";
                if (i < 9) lable_num = "label5" + (i + 1);
                else lable_num = "label6" + (i - 9);
                var lableNum = this.Controls.Find(lable_num, true).FirstOrDefault() as Label;
                lableNum.Visible = false;

            }
        }



        /// <summary>
        /// 连接地址显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lab_NowState_MouseHover(object sender, EventArgs e)
        {
            ToolTip toolTip = new ToolTip();
            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 500;
            toolTip.ReshowDelay = 500;
            toolTip.SetToolTip(this.lab_NowState, axisparam.IP);
        }

        /// <summary>
        /// 点位运动加载轴选项
        /// </summary>
        /// <param name="IsConnect">连接状态</param>
        /// <param name="MotorMaxNum">控制卡轴数量</param>
        public void loadPointSport(bool IsConnect, int MotorMaxNum)
        {
            for (int i = 0; i < MotorMaxNum; i++)
            {
                comSelectAxis0.Items.Add(i + 1);
                comSelectAxis1.Items.Add(i + 1);
                comSelectAxis2.Items.Add(i + 1);
                comSelectAxis3.Items.Add(i + 1);
            }
            comSelectAxis0.Text = "";
            comSelectAxis1.Text = "";
            comSelectAxis2.Text = "";
            comSelectAxis3.Text = "";
            txtSelectPoint0.Text = "0";
            txtSelectPoint1.Text = "0";
            txtSelectPoint2.Text = "0";
            txtSelectPoint3.Text = "0";


        }

        //private async Task GoPoinAsync()
        private void GoPoin()
        {
            btnGoPoint.Text= "运动中";
            btnGoPoint.Enabled = false;
            List<int> axislist=new List<int>();
            List<float> points = new List<float>();
            try
            {
                for (int i = 0; i < 4; i++)
                {
                    var c_SelectAxis = "comSelectAxis" + i;
                    var c_SelectPoint = "txtSelectPoint" + i;
                    var SelectAxiss = this.Controls.Find(c_SelectAxis, true).FirstOrDefault() as ComboBox;
                    var SelectPoint = this.Controls.Find(c_SelectPoint, true).FirstOrDefault() as TextBox;
                    if (SelectAxiss.Text != "")
                    {
                        points.Add(Convert.ToSingle(SelectPoint.Text));
                        axislist.Add(Convert.ToInt32(SelectAxiss.Text)-1);
                    }
                }
            
                int[] axisnum = axislist.ToArray();
                float[] pointsnum = points.ToArray();
                PMC_Base(_handle, axisnum.Length, axisnum);
                PMC_MoveAbs(_handle,axisnum.Length,axisnum,pointsnum);
                isPower();
                int[] axisStop = new int[axisnum.Length];
                int j=0;
                foreach (int i in axisnum)
                {
                    while (axisStop[j]==0)
                    {
                        PMC_GetIfIdle(_handle, i,ref axisStop[j]);
                    }
                    j++;
                }
                btnGoPoint.Text = "运动点";
                isPower();
                btnGoPoint.Enabled = true;
            }
            catch (Exception e)
            {
                btnGoPoint.Text = "运动点";
                btnGoPoint.Enabled = true;
                MessageBox.Show($"错误{e}");
            }
        }



        /// <summary>
        /// 轴状态查询
        /// </summary>
        /// <param name="axisPower">轴集合</param>
        /// <param name="isQuery">受否查询轴状态</param>
        public bool isPower(bool isQuery=false)
        {

            int pfValue = -1;
            var data = "";
            for (int i = 0; i < axisparam.MotorMaxNum; i++)
            {
                PMC_GetIfIdle( _handle, i,ref pfValue);     //pfValue=-1:停止；0：运动;
                axisFlag[i] = (pfValue == -1) ? false : true;
                if (isQuery && axisFlag[i])
                {
                    return true;
                }
            }
            return false;
        }

        
    }
}
